package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.helper.CategoryHelper;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.ProductDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.*;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by DK on 16/9/18.
 * 产品 分销市场
 */
@RestController
public class MarketMerchantProductController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MarketMerchantProductController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private CategoryHelper categoryHelper;

    @Autowired
    private MarketMerchantProductSalesRepository marketMerchantProductSalesRepository;

    @Autowired
    private MerchantProductRepository merchantProductRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private MarketMerchantCooperationRepository marketMerchantCooperationRepository;

    @Autowired
    private MerchantProductStatisticsRepository merchantProductStatisticsRepository;

    /**
     * @api {get} /market/merchant/category/list 分销市场 产品品类列表
     * @apiGroup MARKET_PRODUCT
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccess {Long} id 品类ID
     * @apiSuccess {String} name 品类名称
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *      "code": "1",
     *      "desc": "成功"
     *      "data": [
     *           {
     *           "id": 1,
     *           "dateCreated": "2016-01-15 11:25:00",
     *           "lastUpdated": "2016-05-16 19:02:06",
     *           "version": 1,
     *           "name": "美食",
     *           "iconUrl": "/20160516/20160516190202F32y0Nth.png",
     *           "logoUrl": "/20160516/201605161902041HsJiQ6M.png",
     *           "visible": true,
     *           "displayOrderId": 3,
     *           "mallId": 1
     *           },
     *       ]
     * }
     */
    @RequestMapping(value = Routes.MARKET_MERCHANT_CATEGORY_LIST, method = RequestMethod.GET)
    public JsonResult categoryList(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            List<Category> categoryList = categoryRepository.findByMallIdAndVisibleAndIsDeleteAndParentIdIsNull(userInfoDto.mall.getId(), true, Whether.NO);
            jsonResult.data = categoryList;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /market/merchant/sale_product/page 分销市场 产品查询分页
     * @apiGroup MARKET_PRODUCT
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String=NO("不显示"), 为空("显示")} showSaleProduct 是否显示已分销产品
     * @apiParam {String=ASC("升序"), DESC("降序")} sort 排序(sortByName为空则sort为空,sortByName传值则sort传值)
     * @apiParam {String=date_created("发布时间") resell_fee("佣金") sell_price("售价"), quantity("数量")} sortByName 按字段排序
     * @apiParam {String} keyword 产品编号/名称/商家名称
     * @apiParam {String=SERVICE("服务"), GOODS("商品"), ALL("全部")} type <code>必须参数</code> 产品类型 默认 ALL
     * @apiParam {Long} categoryId 品类 默认全部传空, 其他情况传值调/market/merchant/product/category 返回ID值
     *
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize
     *
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} type 产品类型
     * @apiSuccess {String} name 产品名称
     * @apiSuccess {BigDecimal} basePrice 原价
     * @apiSuccess {BigDecimal} sellPrice 出售价
     * @apiSuccess {Long} quantity 库存量
     * @apiSuccess {BigDecimal} carriage 运费
     * @apiSuccess {boolean} refundable 是否支持过期退
     * @apiSuccess {boolean} sellnow 是否立即开售
     * @apiSuccess {Date} dateSelling 开售时间
     * @apiSuccess {Long} limitCount 限购数
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {String} note 卖点介绍
     * @apiSuccess {String=SELLING("在售"), SOLDOUT("已下架"), EXPIRED("已过期"), DELETED("已删除"), WAIT_APPLY("待申请"), WAIT_AUDIT("待审核"), AUDIT_PASS("审核通过"), AUDIT_FAIL("审核不通过")} status 产品状态
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String=SHOP_PICKUP("到店自取"), SHIPPING("物流"), SHOP_PICKUP_AND_SHIPPING("物流及到店自取")} shippingType 支持的物流类型
     * @apiSuccess {String} marketId 分销产品唯一的识别码
     * @apiSuccess {String} marketProductType 分销市场属性
     * @apiSuccess {String} extSourceId 供应商ID
     * @apiSuccess {String} marketPlatformType 平台属性
     * @apiSuccess {String} merchantName 商家名称
     * @apiSuccess {String} resellFee 分销佣金
     * @apiSuccess {String} shareFee 分享返利
     * @apiSuccess {Date} dateEnabled 有效期开始时间
     * @apiSuccess {Date} dateDisabled 有效期结束时间
     * @apiSuccess {String} isSale 不为空,已分销
     * @apiSuccess {String=WAIT("等待审核"), PASS("审核通过"), REFUSE("没合作关系")} cooperation 不为空,已分销
     *
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *       "data": [
     *           {
     *               "id": 71,
     *               "dateCreated": "2016-06-01 14:13:43",
     *               "lastUpdated": "2016-07-22 10:49:28",
     *               "type": "GOODS",
     *               "name": "宇宙",
     *               "basePrice": 110,
     *               "sellPrice": 100,
     *               "quantity": 998,
     *               "carriage": 0,
     *               "refundable": false,
     *               "sellnow": true,
     *               "dateSelling": "2016-06-01 14:13:43",
     *               "limitCount": 0,
     *               "logoUrl": "/20160601/201606011413084VOvLKgN.jpg",
     *               "note": "全宇宙最漂亮的",
     *               "status": "SELLING",
     *               "mallId": 1,
     *               "merchantId": 1,
     *               "serveRate": "2.4",
     *               "shippingType": "SHIPPING",
     *               "resellFee": 5,
     *               "shareFee": 2,
     *               "identifier": "dfsdwrwers334rnwfu"
     *               "marketIdentifier": "36ca173cd8cc74f8233898909f7a242c",
     *               "marketProductType": "TARGET",
     *               "marketPlatformType": "OUT_PLATFORM",
     *               "extSourceId": "29"
     *               "dateEnabled": "2016-06-01 14:13:43"
     *               "dateDisabled": "2016-06-01 14:13:43"
     *               "isSale": "134",
     *               "cooperation" : "WAIT"
     *           }
     *       ],
     *       "totalCount": 24,
     *       "totalPage": 24,
     *       "pageNo": 0,
     *       "pageSize": 1
     *       }
     *   }
     *
     */
    @RequestMapping(value = Routes.MARKET_MERCHANT_SALE_MARKET_PAGE, method = RequestMethod.GET)
    public JsonResult saleMarketPage(HttpServletRequest request, ProductDto productDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String type = productDto.getType();
            if (StringUtils.isBlank(type) || !EnumUtils.isValidEnum(ProductType.class, type)) {
                jsonResult.remind("产品类型只允许 SERVICE(\"服务\"), GOODS(\"商品\"), ALL(\"全部\")",log);
                return;
            }
            //分类不为空
            List<Long> categoryIds = new ArrayList<>();
            Long anUserInfoDtomallId = userInfoDto.mall.getId();
            if (productDto.getCategoryId() != null) {
                categoryIds = categoryHelper.categoryIds(anUserInfoDtomallId, Arrays.asList(productDto.getCategoryId()), null);
                if (categoryIds.size() == 0) {
                    categoryIds.add(productDto.getCategoryId());
                }
            }

            String keyword = productDto.getKeyword();
            String sortByName = productDto.getSortByName();
            String sort = productDto.getSort();
            String showSaleProduct = productDto.getShowSaleProduct();
            Long anUserInfoDtomerchantId = userInfoDto.merchant.getId();
            PageResult page = this.getPage(productDto.getPageNo(), productDto.getPageSize());
            PageResult<ProductDto> pageResult = merchantProductRepository.findSaleMarketPage(keyword, type, categoryIds, sortByName, sort, showSaleProduct, anUserInfoDtomerchantId, anUserInfoDtomallId, page);
            pageResult.data.stream().map(dto -> {
                MarketMerchantCooperation marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(dto.getMerchantId(), anUserInfoDtomerchantId, MarketMerchantCooperationStatus.REFUSE);
                dto.setMarketMerchantCooperationStatus(MarketMerchantCooperationStatus.REFUSE.toString());
                if(marketMerchantCooperation != null){
                    dto.setMarketMerchantCooperationStatus(marketMerchantCooperation.getStatus().toString());
                }
                return dto;
            }).collect(Collectors.toList());
            pageResult.setUrl(Routes.MARKET_MERCHANT_SALE_MARKET_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /market/merchant/sale_product 分销市场 我要分销
     * @apiGroup MARKET_PRODUCT
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} id 产品id
     *
     * @apiSuccess {String=1("成功"), 10("商家没有合作关系")} code 返回码
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *      "code": "1",
     *      "desc": "成功"
     * }
     *
     */
    @Transactional
    @RequestMapping(value = Routes.MARKET_MERCHANT_SALE_PRODUCT, method = RequestMethod.POST)
    public JsonResult saleProduct(HttpServletRequest request, @RequestBody ProductDto productDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            if (productDto.getId() == null) {
                jsonResult.errorParam(Product.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }

//            需求有改:入驻平台已签订协仪,故将代码注释
//            MarketMerchant marketMerchant = marketMerchantRepository.findByMerchantIdAndMallId(userInfoDto.merchant.getId(), userInfoDto.mall.getId());
//            if (marketMerchant == null || !marketMerchant.getSaleProtocolStatus()) {
//                jsonResult.remind("您还没有签订分销协议");
//                return;
//            }
            Product product = merchantProductRepository.findOne(productDto.getId());
            if (product == null) {
                jsonResult.remind(Product.REMIND_RECORD_IS_NOT_EXIST,log);
                return;
            }

            Long productMerchantId = product.getMerchantId();
            Long anUserInfoDtomerchantId = userInfoDto.merchant.getId();
            if (productMerchantId == anUserInfoDtomerchantId) {
                jsonResult.remind("自己产品无法分销",log);
                return;
            }

            Merchant merchant = merchantRepository.findOne(productMerchantId);
            Long productMallId = product.getMallId();
            Long anUserInfoDtomallId = userInfoDto.mall.getId();
            if (merchant.getProdAudit()) {
                MarketMerchantCooperation marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(productMerchantId, anUserInfoDtomerchantId, MarketMerchantCooperationStatus.REFUSE);
                if (marketMerchantCooperation == null) {
                    jsonResult.remind("商家没有合作关系", log);
                    return;
                }
                if (MarketMerchantCooperationStatus.REFUSE == MarketMerchantCooperationStatus.valueOf(marketMerchantCooperation.getStatus().toString())) {
                    jsonResult.remind("商家没有合作关系", log);
                    return;
                }
                MarketMerchantProductSales merchantProductSales = marketMerchantProductSalesRepository.findByProductIdAndDistributorMerchantIdAndIsDeleteAndSupplierStatusAndDistributorStatus(productDto.getId(), anUserInfoDtomerchantId, Whether.NO, MarketMerchantProductSalesStatus.PASS, MarketMerchantProductSalesStatus.PASS);
                if (merchantProductSales != null) {
                    jsonResult.remind("你已分销了此产品", log);
                    return;
                }
            } else {
                // 当不需要合作审核时,分销产品需要主动添加他们的合作关系
                MarketMerchantCooperation marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(productMerchantId, anUserInfoDtomerchantId, MarketMerchantCooperationStatus.REFUSE);
                if (marketMerchantCooperation == null) {
                    marketMerchantCooperation = new MarketMerchantCooperation();
                    marketMerchantCooperation.setDistributorMallId(anUserInfoDtomallId);
                    marketMerchantCooperation.setDistributorMerchantId(anUserInfoDtomerchantId);
                    marketMerchantCooperation.setSupplierMallId(productMallId);
                    marketMerchantCooperation.setSupplierMerchantId(productMerchantId);
                }
                marketMerchantCooperation.setStatus(MarketMerchantCooperationStatus.PASS);
                marketMerchantCooperationRepository.save(marketMerchantCooperation);
            }

            //保存分销产品到商家中
            Product marketProduct = new Product();
            RBeanUtils.copyProperties(product, marketProduct, "id", "dateCreated", "lastUpdated", "cAccessUrl", "promoteUrl");
            marketProduct.setMarketId(product.getId());//当marketId 存在时,证明产品是分销的
            marketProduct.setMerchantId(userInfoDto.merchant.id);
            marketProduct.setShareFee(BigDecimal.ZERO); //分享返利值为0,刚分销过来的时候
            marketProduct.setMallId(anUserInfoDtomallId);
            marketProduct.setMarketMallId(productMallId);
            marketProduct.setMarketMerchantId(productMerchantId);
            marketProduct.setMarketMerchantName(product.getMerchantName());
            marketProduct.setMerchantName(userInfoDto.merchant.getName());
            marketProduct.setMarketPlatformType(ProductMarketPlatformType.IN_PLATFORM);
            if (productMallId != anUserInfoDtomallId) {
                marketProduct.setMarketPlatformType(ProductMarketPlatformType.OUT_PLATFORM);
            }
            marketProduct = merchantProductRepository.save(marketProduct);

            //产品统计表
            ProductStatistics productStatistics = new ProductStatistics();
            productStatistics.setMallId(marketProduct.getMallId());
            productStatistics.setMerchantId(marketProduct.getMerchantId());
            productStatistics.setProductId(marketProduct.getId());
            productStatistics.setMarketProductId(product.getId());
            merchantProductStatisticsRepository.save(productStatistics);

            // 分销关系表 插入一条记录
            MarketMerchantProductSales productSales = new MarketMerchantProductSales();
            productSales.setProductId(product.getId());
            productSales.setDistributorMallId(userInfoDto.merchant.getMallId());
            productSales.setDistributorMerchantId(anUserInfoDtomerchantId);
            productSales.setDistributorStatus(MarketMerchantProductSalesStatus.PASS);
            productSales.setSupplierMallId(productMallId);
            productSales.setSupplierMerchantId(productMerchantId);
            productSales.setSupplierStatus(MarketMerchantProductSalesStatus.PASS);

            marketMerchantProductSalesRepository.save(productSales);
        };
        return doing.go(request, log);
    }
}
